<template>
  <div class="wrap">
    <div class="wrap-button" style="height: 28px">
      <a-button type="primary" @click="handleAdd">新建</a-button>
      <div style="float: right">
        <a-select
          v-if="isSuperAdmin"
          placeholder="选择租户"
          v-model:value="recordSo.tenantId"
          style="width: 180px; margin-right: 8px"
          allowClear
          @change="handleChangeTenant"
        >
          <a-select-option v-for="item in tenants" :key="item.id" :value="item.id">{{
            item.name
          }}</a-select-option>
        </a-select>
        <a-input
          v-model:value="recordSo.keyword"
          style="width: 180px; margin-right: 8px"
          placeholder="输入关键字查询"
          allow-clear
        >
          <template #prefix>
            <user-outlined />
          </template>
        </a-input>
        <a-button type="primary" style="margin-right: 8px" @click="list">查询</a-button>
        <a-button type="primary" @click="handleSearch">导出</a-button>
      </div>
    </div>
    <div style="flex: 1; margin-top: 16px">
      <a-table
        :loading="loading"
        :dataSource="data"
        :columns="columns"
        :pagination="pagination"
        size="middle"
        @change="handleTableChange"
        :scroll="{ x: 'max-content' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'dataSource'">
            <a-tag v-if="record.dataSource === 1" color="cyan">开始</a-tag>
            <a-tag v-else-if="record.dataSource === 2" color="cyan">结束</a-tag>
            <a-tag v-else-if="record.dataSource === 3" color="cyan">暂停</a-tag>
            <a-tag v-else-if="record.dataSource === 4" color="cyan">段数据</a-tag>
            <a-tag v-else-if="record.dataSource === 5" color="cyan">定时</a-tag>
            <a-tag v-else color="red">未知</a-tag>
          </template>
          <template v-if="column.key === 'pileStatus'">
            <a-tag v-if="record.pileStatus === 1" color="cyan">停钻</a-tag>
            <a-tag v-else-if="record.pileStatus === 2" color="cyan">下钻</a-tag>
            <a-tag v-else-if="record.pileStatus === 3" color="cyan">提钻</a-tag>
            <a-tag v-else-if="record.pileStatus === 4" color="cyan">复下</a-tag>
            <a-tag v-else-if="record.pileStatus === 5" color="cyan">复提</a-tag>
            <a-tag v-else color="red">未知</a-tag>
          </template>
          <template v-if="column.key === 'status'">
            <a-tag v-if="record.status === '0'" color="cyan">前期</a-tag>
            <a-tag v-else-if="record.status === '1'" color="cyan">施工</a-tag>
            <a-tag v-else color="cyan">完工</a-tag>
          </template>
          <template v-if="column.key === 'operation'">
            <a-button
              class="button-interval"
              type="link"
              :icon="h(EditOutlined)"
              @click="showEditModal(record)"
              size="small"
            >
              修改
            </a-button>
          </template>
        </template>
      </a-table>
      <a-modal
        v-model:visible="open"
        :title="type === 'add' ? '新增项目' : '修改项目'"
        @ok="submitAdd"
      >
        <a-form
          ref="formRef"
          style="margin-top: 24px"
          :model="formState"
          name="basic"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
          autocomplete="off"
        >
          <a-form-item
            label="项目名称"
            name="name"
            :rules="[{ required: true, message: 'Please input tenant name!' }]"
          >
            <a-input
              readOnly
              onfocus="this.removeAttribute('readonly');"
              onblur="this.setAttribute('readonly',true);"
              v-model:value="formState.name"
            />
          </a-form-item>
          <a-form-item label="负责人" name="manager">
            <a-input v-model:value="formState.manager" />
          </a-form-item>
          <a-form-item label="联系方式" name="managerTel">
            <a-input v-model:value="formState.managerTel" />
          </a-form-item>
          <a-form-item label="监理单位" name="supervisor">
            <a-input v-model:value="formState.supervisor" />
          </a-form-item>
          <a-form-item label="施工单位" name="builder">
            <a-input v-model:value="formState.builder" />
          </a-form-item>
          <a-form-item label="项目地址" name="address">
            <a-input v-model:value="formState.address" />
          </a-form-item>
          <a-form-item label="项目状态" name="status">
            <a-select ref="select" v-model:value="formState.status">
              <a-select-option value="0">前期</a-select-option>
              <a-select-option value="1">施工</a-select-option>
              <a-select-option value="2">完工</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="所属租户" name="tenantId">
            <a-select ref="select" v-model:value="formState.tenantId">
              <a-select-option v-for="item in tenants" :key="item.id" :value="item.id">{{
                item.name
              }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { h, ref, onMounted, reactive, watch, computed } from 'vue'
  import {
    DeleteOutlined,
    SettingOutlined,
    EditOutlined,
    EllipsisOutlined,
  } from '@ant-design/icons-vue'
  import { FormInstance, message } from 'ant-design-vue'
  import { BaseTitle } from '/@/components/Title'
  import { pageProject, createProject } from '/@/api/pd/project'
  import { ProjectListResult, ProjectBO, ProjectSO } from '/@/api/pd/model/projectModel'
  import { Modal } from 'ant-design-vue'
  import Echarts from '/@/components/ReEcharts/index.vue'
  import { EChartsOption } from 'echarts'
  import type { Dayjs } from 'dayjs'
  import { listTenant } from '/@/api/sys/tenant'
  import { TenantModel } from '/@/api/sys/model/tenantModel'
  import { useUserStore } from '/@/store/modules/user'
  import { is } from '/@/utils/is'

  const open = ref<boolean>(false)
  const openPermission = ref<boolean>(false)
  const loading = ref(false)
  const showBaseFlag = ref(true)
  const hideText = ref('收起')
  const value1 = ref('a')
  const type = ref('add')
  const expandedRowKeys = ref<string[]>([])
  type RangeValue = [Dayjs, Dayjs]
  const value2 = ref<RangeValue>()
  const tenants = ref<TenantModel[]>([])
  const userStore = useUserStore()
  const isSuperAdmin = userStore.getSuperAdmin

  const pagination = ref({
    total: 0,
    current: 1,
    pageSize: 15,
    size: '',
    showSizeChanger: false,
    showQuickJumper: false,
  })

  const formRef = ref<FormInstance>()

  let formState = reactive<ProjectBO>({
    name: '',
    manager: '',
    managerTel: '',
    tenantId: '',
    supervisor: '',
    builder: '',
    address: '',
    status: '',
  })

  let recordSo = reactive<ProjectSO>({
    keyword: undefined,
    tenantId: isSuperAdmin ? undefined : userStore.getUserInfo.tenantId,
  })

  const pageParam = computed(() => ({
    query: recordSo,
    current: pagination.value?.current,
    size: pagination.value?.pageSize,
  }))

  const columns = [
    {
      title: '项目名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      width: 140,
      fixed: 'left',
    },
    {
      title: '租户名称',
      dataIndex: 'tenantName',
      key: 'tenantName',
      align: 'center',
      width: 80,
    },
    {
      title: '负责人',
      dataIndex: 'manager',
      key: 'manager',
      align: 'center',
      width: 80,
    },
    {
      title: '联系方式',
      dataIndex: 'managerTel',
      key: 'managerTel',
      align: 'center',
      width: 80,
    },
    {
      title: '监理单位',
      dataIndex: 'supervisor',
      key: 'supervisor',
      align: 'center',
      width: 80,
    },
    {
      title: '施工单位',
      dataIndex: 'builder',
      key: 'builder',
      align: 'center',
      width: 80,
    },
    {
      title: '项目地点',
      dataIndex: 'address',
      key: 'address',
      align: 'center',
      width: 80,
    },
    {
      title: '项目状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 80,
    },
    {
      title: '设备数量',
      dataIndex: 'deviceCount',
      key: 'deviceCount',
      align: 'center',
      width: 120,
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      align: 'center',
      width: 80,
    },
  ]

  let data = ref<ProjectListResult[]>([])

  let checkedKeys = ref<string[]>(['3'])

  interface Props {
    width?: string
    height?: string
    option: EChartsOption
  }
  const props = withDefaults(defineProps<Props>(), {
    width: '100%',
    height: '100%',
    option: () => ({}),
  })

  watch(checkedKeys, () => {
    console.log('checkedKeys', checkedKeys)
  })

  //#endregion

  onMounted(() => {
    if (isSuperAdmin) initTenant()
    list()
  })

  async function list() {
    loading.value = true
    const res = await pageProject(pageParam.value)
    console.log('res', res)
    data.value = res.records
    pagination.value.total = Number(res.total)
    pagination.value.current = Number(res.current)
    loading.value = false
  }

  const reload = () => {
    pageParam.value.current = 1
    list()
  }

  function handleTableChange(page) {
    pagination.value.current = page.current
    list()
  }

  function initTenant() {
    listTenant().then((res) => {
      tenants.value = res
    })
  }

  const handleChangeTenant = () => {
    list()
  }

  const showEditModal = (record) => {
    type.value = 'edit'
    formState = record
    open.value = true
  }
  const handleAdd = () => {
    type.value = 'add'
    open.value = true
  }

  const submitAdd = () => {
    createProject(formState).then(() => {
      message.success('新增成功')
      reload()
    })
  }

  //#endregion
</script>

<style lang="scss" scoped>
  .wrap {
    max-width: calc(100vw - 230px);
    &-table {
      margin-top: 16px;
    }
  }

  .base-enter-active,
  .base-leave-active {
    transition: opacity 0.4s;
  }
  .base-enter,
  .base-leave-active {
    opacity: 0;
  }
</style>
